<%@ page language="java" import="java.util.*,org.apache.struts2.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"   %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
%>
<!DOCTYPE HTML>
<html>
<head>
	<title></title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link href="<%=basePath %>/assets/css/dpl-min.css" rel="stylesheet" type="text/css" />
	<link href="<%=basePath %>/assets/css/bui-min.css" rel="stylesheet" type="text/css" />
    <link href="<%=basePath %>/assets/css/page-min.css" rel="stylesheet" type="text/css" /> 
	<style type="text/css">
	 #grid,#btnSave,.row{
	 	margin-top:10px;
	 	margin-left:20px;
	 }
	 #loding{
	 	width:100%;
	 	height:100%;
	 	background:transparent;
	 	z-index:2000;
	 	text-align: center;
	 	display: none;
	 	position: absolute;
	 }
	 #J_Form{
	 	width:100%;
	 }
	 /**内容超出 出现滚动条 **/
    .bui-stdmod-body{
      overflow-x : hidden;
      overflow-y : auto;
    }
	</style>
</head>
<body>
    <div id="grid" ></div>
    <div id="content" class="hide" style="height:500px;">
	<form id="J_Form"  class="form-horizontal" method="post">
	  <input name="id" type="hidden">
      <div class="control-group">
        <label class="control-label"><s>*</s>子类名称:</label>
        <div class="controls" style="width:80%">
          <input name="name" type="text" class="input-large" data-rules="{required : true}" data-messages="{required:'子类名称不能为空'}">
        </div>
      </div>
      <div class="control-group" >
        <label class="control-label"><s>*</s>子类简介:</label>
        <div class="controls  control-row-auto">
          <textarea name="info"  class="control-row5 input-large"></textarea>
        </div>
      </div>
      <div class="control-group" >
        <label class="control-label"><s>*</s>属于的主类:</label>
        <div class="controls  control-row-auto">
			<select id="select" disabled="disabled" onchange="getSelectedToRoot_id()">
			</select>
        </div>
        <a onclick="getRootSort()" style="margin-left:5px;">获取资源</a>
        <input name="root_id"  type="hidden" value="" data-rules="{required : true}" data-messages="{required:'请选择主类'}" id="root_id"/>
        <span id="select_state" Style="display:none;"></span>
      </div>
      <div class="control-group" style="margin-bottom: 150px;">
        <label class="control-label"><s>*</s>上传图片:</label>
        <div class="controls">
          	<input id="img" type="hidden" name="img" value="" data-rules="{required : true}" data-messages="{required:'请上传图片'}">
	      	<div id="J_Uploader">
        </div>
      	</div>
      </div>
    </form>
    </div>
</body>
	<script type="text/javascript" src="<%=basePath %>/assets/js/jquery-1.8.1.min.js"></script>
	<script type="text/javascript" src="<%=basePath %>/assets/js/bui.js"></script>
	<script type="text/javascript" src="<%=basePath %>/assets/js/config.js"></script>
    <script type="text/javascript">
    
    
    	//设定BUI视图变量
    	var Grid = BUI.Grid;
    	//设定BUI数据变量
        var Data = BUI.Data;
        //获取数据
        var Store = Data.Store;
        //定义columns并且初始化
        var columns = [
          //table columns
          {title : '子类名字',dataIndex :'name',width:'20%'},
          {title : '子类介绍',dataIndex :'info',width:'80%'},
          {title : '属于主类',dataIndex :'root_name',width:'20%'},
          {title : '子类图片',dataIndex :'img',width:'20%',renderer : function(value){
                  return '<a class="hover-view-img" title="'+value+'" >显示图片</a>';
                }},
          //和添加编辑按钮
		  {title : '操作',renderer : function(){
		    return '<span class="grid-command btn-edit">编辑</span>&nbsp;&nbsp;&nbsp;<a href="#" class="btn-del" style="color:red;">删除</a>';
		  }},
        ];
        
        //定义store并且通过AJAX获取数据
        var store = new Store({
        	//AJAX 提交路劲
            url : '<%=basePath %>/Json/SubSort',
            //自动加载数据
            autoLoad:true,
            //从第0个元素开始获取信息 
            start:0,
            //配置分页数目,后台相当于limit参数
            pageSize:15
          });
          
		//定义编辑器并且设定自定义按钮
		var editing = new Grid.Plugins.DialogEditing({
		 	//设置隐藏的Dialog内容
            contentId : 'content',
            //触发显示Dialog的样式
            triggerCls : 'btn-edit',
            //编辑器 
            editor : {
              width:'90%',
              height:350,
              //编辑器标题
              title : '内容编辑',
              //设置自定义按钮
              buttons : [
              	//确定按钮
              	{
              		text:'确定',
              		elCls : 'button button-primary',
              		handler : function(){
						//实现ajax数据提交
						$.ajax({
							type:"post",
							dataType:"json",
							data:{
								'id':editing.get('form').getFieldValue('id'),
								'name':editing.get('form').getFieldValue('name'),
								'info':editing.get('form').getFieldValue('info'),
								'root_id':$("#root_id").val(),
								'img':$("#img").attr("value"),
							},
							url:"<%=basePath %>/SubSort_JEdit",
							beforeSend: function(XMLHttpRequest){
								//显示稍等
								$("#loding").css("display","block");
							},
							success: function(data){
								//成功并且收到信息
								if(data==1){
									$("#loding").css("display","none");
									//隐藏稍等窗口
									BUI.Message.Alert('恭喜您,编辑成功!',function(){
										refreshFunction();
									},'success');
									//刷新
								}else{
									$("#loding").css("display","none");
									//隐藏稍等窗口
									BUI.Message.Alert('编辑失败，请重试！',function(){
										refreshFunction();
									},'error');
								}
							},
							error: function(status){
								if (status == "timeout")
				                {
				                	$("#loding").css("display","none");
				                	BUI.Message.Alert('请求超时，请重试!',function(){
										refreshFunction();
									},'error');
				                }else{
				                	$("#loding").css("display","none");
				                	//如果出别的错
									BUI.Message.Alert('系统错误，请跟管理员联系！',function(){
										refreshFunction();
									},'error');
				              	}
							}
						});
						//消失弹出窗口
						this.hide();
              		},
              	},
              	//取消按钮
              	{
              		text:'取消',
              		elCls : 'button',
              		handler : function(){
              			this.hide();
              		}
              	}
              ]
            }
          });

        //定义视图并且设置视图配置
        var grid = new Grid.Grid({
        	//显示div的id
            render:'#grid',
            //宽度
            width:'99.7%',
            //加载columns
            columns : columns,
            //加载数据时显示屏蔽层
            loadMask: true, 
            //加载store
            store: store,
            //给grid加载CheckSelection和编辑器
            plugins : [editing],
            // 底部工具栏
            bbar:{
                // pagingBar:表明包含分页栏
                pagingBar:true,
            },
            // 顶部工具栏
            tbar:{
		      items : [
		      	//添加刷新按钮
		      	{
			        btnCls : 'button button-small',
			        text : '<i class="icon-refresh" tyle="color:blue"></i>刷新',
			        listeners : {
			          'click' : refreshFunction
			        }
		      	}
		      ]
		    }
        });
        
        //item点击事件
        grid.on('itemclick',function(ev){
	        var sender = $(ev.domTarget);
	        //获取点击的item
	        var item = ev.item;
	        //点击删除操作
	        if(sender.hasClass('btn-del')){
	        	//执行删除函数
	        	delFunction(item);
	        }else if(sender.hasClass('btn-edit')){
	        	//清空主类选择器
	        	$("#select").empty();
	        	$("#select").append("<option value='0' id='select_0'>请先获取主类信息</option>");
	        	$("#select").attr("disabled","disabled");
	        	//初始化上传函数
				editUpload(item);
	        }
        });  
          
        //加载grid
        grid.render();
        
        //上传文件
        var queue = null;
       	BUI.use('bui/uploader',function (Uploader) {
       	
       		  //带图片预览的主题
			  Uploader.Theme.addTheme('mytheme', {
			    elCls: 'imageViewTheme',
			    queue:{
			      resultTpl: {
			          'default': '<div class="default">{name}</div>',
			          'success': '<div data-url="{url}" class="success_url"><img src="<%=basePath%>{url}" title="{name}" style="width:100%;height:100%;"></div>',
			          'error': '<div class="error"><span title="{name}">{msg}</span></div>',
			          'progress': '<div class="progress"><div class="bar" style="width:{loadedPercent}%"></div></div>'
			      }
			    }
			  });
       	
		     var uploader = new Uploader.Uploader({
		       render: '#J_Uploader',
		       url: '<%=basePath%>/SubSort_JUpload',
		       //指定使用主题
        	   theme: 'mytheme',
		       rules: {
		         //文的类型
		         ext: ['.png,.jpg','文件类型只能为{0}'],
		         //上传的最大个数
		         max: [1, '文件的最大个数不能超过{0}个'],
		         //文件大小的最小值,这个单位是kb
		         minSize: [0, '文件的大小不能小于{0}KB'],
		         //文件大小的最大值,单位也是kb
		         maxSize: [1024, '文件大小不能大于1M']
		       },
		       multiple:false,
		       isSuccess: function(res){
		       		$("#img").attr("value",res.url);
		       		return true;
		       }
		      }).render();
		      queue = uploader.get('queue');
	   });
	   
	   //显示图片
		BUI.use('bui/tooltip',function (Tooltip) {
			var tips = new Tooltip.Tips({
	        	tip : {
		          trigger : '.hover-view-img', //出现此样式的元素显示tip
		          alignType : 'bottom-left', //默认方向
		          titleTpl : '<img src="<%=basePath %>/{title}">',
		          offset : 10 //距离左边的距离
		        }
		      });
	      tips.render();
		});
        
        //编辑以上传的图片
        function editUpload(item){
        	var list = new Array();
         	//设置文件的回显   
       		var temp = {
       			success: true,
       			name: item.img,
       			url: item.img,
       			ext:'.jpg'
       		};
       		list.push(temp);
         	queue.setItems(list);
        }
        
        //删除函数
        function delFunction(item){
        	BUI.Message.Confirm('你确定删除此数据吗?',function(){
          		setTimeout(function(){
          			//实现ajax数据提交
						$.ajax({
							type:"post",
							dataType:"json",
							data:{
								'id':item.id,
							},
							url:"<%=basePath %>/SubSort_JDelete",
							beforeSend: function(XMLHttpRequest){
								//显示稍等
								$("#loding").css("display","block");
							},
							success: function(data){
								//成功并且收到信息
								if(data==1){
									$("#loding").css("display","none");
									//隐藏稍等窗口
									BUI.Message.Alert('恭喜您,编辑成功!',function(){
										refreshFunction();
									},'success');
								}else{
									$("#loding").css("display","none");
									//隐藏稍等窗口
									BUI.Message.Alert('删除失败，请重试!',function(){
										refreshFunction();
									},'error');
								}
							},
							error: function(status){
								if (status == "timeout")
				                {
				                	$("#loding").css("display","none");
				                    BUI.Message.Alert('请求超时，请重试!',function(){
										refreshFunction();
									},'error');
				                }else{
				                	$("#loding").css("display","none");
				                	//如果出别的错
									BUI.Message.Alert('系统错误，请跟管理员联系！',function(){
										refreshFunction();
									},'error');
				              	}
							}
						});
          		});
        	},'question');
        }
        
        //刷新函数
        function refreshFunction(){
        	location.reload();
        }
        
		//改select值
        function getSelectedToRoot_id(){
        	var res=$("#select option:selected").val();
        	if(res!=0){
        		$("#root_id").val(res);
        	}else{
        		$("#root_id").val("");
        	}
        }
        
        //获取主类
        function getRootSort(){
              //先清空
         	  $("#select").empty();
        	  //加载主类
			  $.ajax({
	             type: "GET",
	             url: "<%=basePath%>/RootSort_JGetNameAndId",
	             dataType: "json",
	             beforeSend:function(XMLHttpRequest){
	             	$("#select_state").css("dispaly","block");
	             	$("#select_state").append("<a id='loding_temp'>正在加载...</a>");
	             	$("#select").attr("disabled","disabled");
	             },
	             success: function(data){
	             	if(data.length==0){
	             		$("#loding_temp").remove();
	             		$("#select_state").css("display","block");
	             		$("#select_state").append("<a style='color:red;margin-left:10px;'>主类为空,请先添加主类!</a>");
	             	}else{
			       		$("#viewimg").css("display","block");
			       		$("#viewimg").attr("src","<%=basePath%>/"+$("#img").val());
	             		//获取RootSort
		           		for(var i=0;i<data.length;i++){
		           			//从隐藏的root_id INPUT 中获取值给SELECT默认值
		           			if(data[i].id==$("#root_id").val()){
		           				$("#select").append("<option selected='selected' value ='"+data[i].id+"'>"+data[i].name+"</option>");
		           			}else{
		           				$("#select").append("<option  value ='"+data[i].id+"'>"+data[i].name+"</option>");
		           			}
		           		}
		           		$("#select").removeAttr("disabled");
	           		}
	             },
	             error:function(XMLHttpRequest, textStatus, errorThrown){
	                    $("#loding_temp").remove();
	             		$("#select_state").css("display","block");
	             		$("#select_state").append("<a style='color:red;margin-left:10px;'>发生错误,请联系管理员!</a>");
	             }
	         });
        }
    </script>
</html>
